import { lazyLoad } from '@/components/loadable';

export const formatRoutes = (
  routes: RouteDataStatic[],
  parentPath = '/',
  parentNoAuth: boolean = false
): RouteData[] => {
  const result: RouteData[] = [];

  routes.forEach((route) => {
    const routeData: RouteData = {
      ...route
    };

    const noAuth = route.noAuth ?? parentNoAuth;

    if (route.path) {
      routeData.path = `${parentPath}${route.path}`;
      routeData.id = routeData.path;

      if (!noAuth) {
        routeData.authority = `admin:${routeData.path}`;
      }
    }

    if (route.element) {
      routeData.element = lazyLoad(route.element!, routeData.authority, routeData.room);
    }

    if (route.children) {
      // 避免开发环境报错
      if (!route.element) {
        routeData.element = null;
      }

      routeData.children = formatRoutes(
        route.children,
        route.path ? `${parentPath}${route.path}/` : parentPath,
        noAuth
      );
    }

    result.push(routeData);
  });

  return result;
};
